package com.emm.yixun.customer.service.impl;
import java.util.ArrayList;
import java.util.List;

import javax.jws.WebService;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.emm.yixun.basic.service.CustomerProjectAnswerService;
import com.emm.yixun.basic.service.CustomerProjectQuestionService;
import com.emm.yixun.common.exception.ResponseCode;
import com.emm.yixun.common.model.CustomerProjectAnswer;
import com.emm.yixun.common.model.CustomerProjectAnswerInfo;
import com.emm.yixun.common.model.CustomerProjectQuestion;
import com.emm.yixun.common.model.CustomerProjectQuestionInfo;
import com.emm.yixun.common.model.dto.CustomerProjectAnswerDto;
import com.emm.yixun.common.model.dto.CustomerProjectQuestionDto;
import com.emm.yixun.common.model.enums.AnswerTypeEnum;
import com.emm.yixun.common.model.enums.DelFlagEnum;
import com.emm.yixun.common.model.enums.IsAvlidEnum;
import com.emm.yixun.common.page.Page;
import com.emm.yixun.common.response.Response;
import com.emm.yixun.common.response.ResponseList;
import com.emm.yixun.customer.service.CustomerProjectQuestionServiceFacade;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Service("customerProjectQuestionServiceFacade")
@WebService(name="com.emm.yixun.customer.service.CustomerProjectQuestionServiceFacade")
public class CustomerProjectQuestionServiceFacadeImpl implements CustomerProjectQuestionServiceFacade{
	private  final Logger   logger = LoggerFactory.getLogger(this.getClass()); 
	
	@Autowired
	private CustomerProjectQuestionService service;
	
	@Autowired
	private CustomerProjectAnswerService customerProjectAnswerService;

	@Override
	public Response<CustomerProjectQuestionDto> save(CustomerProjectQuestionDto dto) {
		Response<CustomerProjectQuestionDto> response=new Response<CustomerProjectQuestionDto>();
		try {
			if(null==dto){
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("保存"));
				return response;
			}
			CustomerProjectQuestionDto mDto=service.create(dto);
			if(null==mDto){
				response.fail("80000", "保存数据错误");
				return response;
			}
			response.success(mDto);
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("保存数据错误：{}",e);
		}
		return response;
	}

	@Override
	public Response<Integer> updateByPrimaryKey(CustomerProjectQuestionDto dto,Boolean selective) {
		Response<Integer> response=new Response<Integer>();
		try {
			if(null==selective || null==dto || null==dto.getId()){
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("更新"));
				return response;
			}
			
			if(selective){
				int count=service.update(dto);
				if(count>0){
					response.success(Integer.valueOf(count));
				}else{
					response.fail("90001", "更新数据失败");
				}
			}else{
				response.fail("90000", "暂未实现,修改参数selective=true即可");
			}
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("更新数据错误：{}",e);
		}
		return response;
	}

	@Override
	public Response<Integer> deleteByPrimaryKey(Long id) {
		Response<Integer> response=new Response<Integer>();
		try {
			if(null==id){
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("删除"));
				return response;
			}
			CustomerProjectQuestionDto mDto=new CustomerProjectQuestionDto();
			mDto.setId(id);
			int count=service.destroy(mDto);
			if(count>0){
				response.success(Integer.valueOf(count));
			}else{
				response.fail("90001", "删除数据失败");
			}
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("删除数据错误：{}",e);
		}
		return response;
	}
	
    @Override
	public Response<CustomerProjectQuestion> findById(Long id) {
		Response<CustomerProjectQuestion> response=new Response<CustomerProjectQuestion>();
		try {
			if(null==id){
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("主键查询"));
				return response;
			}
			CustomerProjectQuestion entity=service.selectById(id);
			if(null==entity){
				response.fail("90001", "主键查询数据失败");
			}else{
				response.success(entity);;
			}
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("主键查询数据错误：{}",e);
		}
		return response;
	}

	@Override
	public ResponseList<CustomerProjectQuestion> findByDto(CustomerProjectQuestionDto dto) {
		ResponseList<CustomerProjectQuestion> response=new ResponseList<CustomerProjectQuestion>();
		try {
			if(null==dto){
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("查询"));
				return response;
			}
			List<CustomerProjectQuestion> list=service.selectListByDto(dto);
			if(null==list){
				response.fail(ResponseCode.NO_DATA_FOUND.getCode(), ResponseCode.NO_DATA_FOUND.formatMessage("查询"));
				return response;
			}
			response.success(list);
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("查询数据错误：{}",e);
		}
		return response;
	}

	@Override
	public Page<CustomerProjectQuestion> findPageByDto(CustomerProjectQuestionDto dto, Integer begin,Integer row) {
		Page<CustomerProjectQuestion> response=new Page<CustomerProjectQuestion>();
		try {
			if(null==dto || null==begin || null==row){
				response.setSuccess(false);
				response.setErrorMsg("参数不合法");
				return response;
			}
			Page<CustomerProjectQuestion> page = service.getPageModel(dto, begin, row);
			if(null==page.getRows()){
				response.setSuccess(false);
				response.setErrorMsg("分页数据不存在");
				return response;
			}
			response=page;
			response.setSuccess(true);
		} catch (Exception e) {
			response.setSuccess(false);
			response.setErrorMsg(ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("查询分页数据错误：{}",e);
		}
		return response;
	}

	@Override
	public ResponseList<CustomerProjectQuestionInfo> questionList(CustomerProjectQuestionDto dto) {
		ResponseList<CustomerProjectQuestionInfo> response=new ResponseList<CustomerProjectQuestionInfo>();
		try {
			if(null==dto){
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("查询"));
				return response;
			}
			List<CustomerProjectQuestionInfo> infoList = new ArrayList<CustomerProjectQuestionInfo>();
			dto.addAsc("sort");
			List<CustomerProjectQuestion> list = service.selectListByDto(dto);
			if(null==list){
				response.fail(ResponseCode.NO_DATA_FOUND.getCode(), ResponseCode.NO_DATA_FOUND.formatMessage("查询"));
				return response;
			}
			//获取答案及其它信息
			for(CustomerProjectQuestion question : list){
				CustomerProjectQuestionInfo info = new CustomerProjectQuestionInfo();
				BeanUtils.copyProperties(question, info);
				
				//查询答案表
				CustomerProjectAnswerDto answerDto = new CustomerProjectAnswerDto();
				answerDto.setCustomerProjectQuestionId(question.getId()); //问题ID
				answerDto.setIsValid(IsAvlidEnum.AVILD.getNo());
				answerDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
				List<CustomerProjectAnswer> answerList = customerProjectAnswerService.selectListByDto(answerDto);
				JSONArray arrayJson = new JSONArray(); //保存答案ID和内容
				JSONArray array = new JSONArray(); //仅保存答案内容
				for(CustomerProjectAnswer answer : answerList){
					JSONObject json = new JSONObject();
					json.put("id", answer.getId());
					json.put("answer", answer.getAnswer());
					arrayJson.add(json);
					array.add(answer.getAnswer());
				}
				info.setAnswer(array.toString());
				info.setArrayJson(arrayJson.toString());
				infoList.add(info);
			}
			response.success(infoList);
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("查询数据错误：{}",e);
		}
		return response;
	}
	
	@Override
    public Page<CustomerProjectQuestionInfo> cusTagPageByDto(CustomerProjectQuestionDto dto, Integer begin,Integer row) {
        Page<CustomerProjectQuestionInfo> response=new Page<CustomerProjectQuestionInfo>();
        try {
            if(null==dto || null==begin || null==row){
                response.setSuccess(false);
                response.setErrorMsg("参数不合法");
                return response;
            }
            Page<CustomerProjectQuestion> page = service.getCusTagPage(dto, begin, row);
            if(null==page.getRows()){
                response.setSuccess(false);
                response.setErrorMsg("分页数据不存在");
                return response;
            }
            List<CustomerProjectQuestion> list = page.getRows();
            Page<CustomerProjectQuestionInfo> pageInfo = new Page<CustomerProjectQuestionInfo>();
            List<CustomerProjectQuestionInfo> infoList = new ArrayList<CustomerProjectQuestionInfo>();
            //获取答案及其它信息
            for(CustomerProjectQuestion question : list){
                CustomerProjectQuestionInfo info = new CustomerProjectQuestionInfo();
                BeanUtils.copyProperties(question, info);
                
                //查询答案表
                CustomerProjectAnswerDto answerDto = new CustomerProjectAnswerDto();
                answerDto.setCustomerProjectQuestionId(question.getId()); //问题ID
                answerDto.setIsValid(IsAvlidEnum.AVILD.getNo());
                answerDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
                List<CustomerProjectAnswerInfo> answerList = customerProjectAnswerService.cusTagByDto(answerDto);
                StringBuffer sb = new StringBuffer();
                for(CustomerProjectAnswerInfo answer : answerList){
                    if(AnswerTypeEnum.INPUT.getNo().equals(answer.getAnswerType()) 
                            || "select_other".equals(answer.getAnswer())){
                        sb.append(answer.getAnswerValue());
                    }else{
                        sb.append(answer.getAnswer());
                        sb.append("&nbsp;&nbsp;");
                    }
                }
                info.setAnswer(sb.toString());
                infoList.add(info);
            }
            pageInfo.setRows(infoList);
            pageInfo.setPageNumber(page.getPageNumber());
            pageInfo.setPageSize(page.getPageSize());
            pageInfo.setTotal(page.getTotal());
            pageInfo.setTotalPages(page.getTotalPages());
            response=pageInfo;
            response.setSuccess(true);
        } catch (Exception e) {
            response.setSuccess(false);
            response.setErrorMsg(ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
            logger.error("查询分页数据错误：{}",e);
        }
        return response;
    }
}
